package com.whccb.apps.office.document.event.receive;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.constant.CallActivityDefinitionConst;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.core.delegate.TaskBehaviorContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.org.cache.DepartmentCache;
import com.actionsoft.bpms.org.model.DepartmentModel;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;

public class SubProcessAfterCompleteEvent extends ExecuteListener {

	public String getDescription() {
		return "收文办理子流程结束后，将子流程的附件同步到主流程，同时将部门经理会签意见反写回主流程。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	@Override
	public void execute(ProcessExecutionContext pec) throws Exception {
		String parentBindid = pec.getProcessInstance().getId();
		TaskBehaviorContext callActivityCtx = (TaskBehaviorContext) pec
				.getParameter(CallActivityDefinitionConst.PARAM_CALLACTIVITY_CONTEXT);
		String subBindid = callActivityCtx.getProcessInstance().getId();

		BO subBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE_DO",
				subBindid);
		BO parentBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
				parentBindid);

		// 根据当前办理人得到其所属部门(HR)
		String uid = callActivityCtx.getUserContext().getUID();
		String hrDeptID = SDK.getRuleAPI().executeAtScript(
				"@getUserExtInfo(" + uid + ",HRSECONDORGID)");
		String awsDeptId = SDK.getRuleAPI().executeAtScript(
				"@getAwsDeptIdByOuterId(" + hrDeptID + ")");
		DepartmentModel dept = DepartmentCache.getModel(awsDeptId);
		// 将子流程的附件上传至父流程的成果字段
		if (subBo != null && parentBo != null) {
			List<FormFile> sourceFormFileList = SDK.getBOAPI().getFiles(
					subBo.getId(), "DOFILE");// 办理部门的成果
			if (sourceFormFileList != null && !sourceFormFileList.isEmpty()
					&& sourceFormFileList.size() > 0) {
				for (FormFile sourceFormFile : sourceFormFileList) {
					if (sourceFormFile != null) {
						// 将文件复制到主流程的成果字段
						FormFileModel parentFormFile = new FormFileModel();
						parentFormFile.setAppId(ODConstant.APP_ID);
						parentFormFile.setCreateDate(new Timestamp(System
								.currentTimeMillis()));
						parentFormFile.setCreateUser(callActivityCtx
								.getUserContext().getUID());
						parentFormFile.setId(UUIDGener.getUUID());
						parentFormFile.setBoId(parentBo.getId());
						parentFormFile.setBoName("BO_WHBK_OD_RECEIVE");
						String fileName = "";
						if (dept != null) {
							fileName = fileName + dept.getName() + "-";
						}
						fileName = fileName
								+ callActivityCtx.getUserContext()
										.getUserName() + "-";
						fileName = fileName + sourceFormFile.getFileName();
						parentFormFile.setFileName(fileName);
						parentFormFile.setBoItemName("DOFILE");
						parentFormFile.setProcessInstId(parentBindid);
						SDK.getBOAPI().upFile(parentFormFile,
								SDK.getBOAPI().getFile(sourceFormFile.getId()));
					}
				}
			}

			// 将部门经理的手签意见上传至父流程
			String parentDCGroupValue = parentBindid;
			String parentDCFileValue = parentBo.getId();
			String subDCGroupValue = subBindid;
			String subDCFileValue = subBo.getId();

			// 构建子流程的签批DC
			String querySubHwDataSql = "SELECT ID,BINDID,BOID,APPID,BOITEMNAME,TASKINSTID,CREATEUSER,CREATETIME,FILENAME,SIGNUSER,SIGNTIME,NOWTYPE,DATA,QRCODE,USERMZ,SORT FROM APP_ACT_HWSIGNATURE_DATA WHERE BINDID = :BINDID  AND BOID =:BOID AND BOITEMNAME = :BOITEMNAME ";
			Map<String, Object> queryMap = new HashMap<String, Object>();
			queryMap.put("BINDID", subBindid);
			queryMap.put("BOID", subBo.getId());
			queryMap.put("BOITEMNAME", "HQ");
			List<Map<String, String>> subHwDataMapList = DBSql.query(
					querySubHwDataSql, queryMap,
					new RowMapper<Map<String, String>>() {
						public Map<String, String> mapRow(ResultSet rs,
								int index) throws SQLException {
							Map<String, String> map = new HashMap<String, String>();
							map.put("ID", rs.getString("ID"));
							map.put("BINDID", rs.getString("BINDID"));
							map.put("BOID", rs.getString("BOID"));
							map.put("APPID", rs.getString("APPID"));
							map.put("BOITEMNAME", rs.getString("BOITEMNAME"));
							map.put("TASKINSTID", rs.getString("TASKINSTID"));
							map.put("CREATEUSER", rs.getString("CREATEUSER"));
							map.put("CREATETIME", rs.getString("CREATETIME"));
							map.put("FILENAME", rs.getString("FILENAME"));
							map.put("SIGNUSER", rs.getString("SIGNUSER"));
							map.put("SIGNTIME", rs.getString("SIGNTIME"));
							map.put("NOWTYPE", rs.getString("NOWTYPE"));
							map.put("DATA", rs.getString("DATA"));
							map.put("QRCODE", rs.getString("QRCODE"));
							map.put("USERMZ", rs.getString("USERMZ"));
							map.put("SORT", rs.getString("SORT"));
							return map;
						}
					});
			if (subHwDataMapList != null && !subHwDataMapList.isEmpty()
					&& subHwDataMapList.size() > 0) {
				for (Map<String, String> subHwDataMap : subHwDataMapList) {
					if (subHwDataMap != null && !subHwDataMap.isEmpty()) {
						String fileName = subHwDataMap.get("FILENAME");
						DCContext subDc = new DCContext(
								UserContext.fromUID("admin"),
								DCProfileManager.getDCProfile(
										ODConstant.HWSIGNATURE_APPID,
										"-hsingature-"), ODConstant.APP_ID,
								subDCGroupValue, subDCFileValue, fileName);
						if (subDc != null) {
							DCContext parentDc = new DCContext(
									UserContext.fromUID("admin"),
									DCProfileManager.getDCProfile(
											ODConstant.HWSIGNATURE_APPID,
											"-hsingature-"), ODConstant.APP_ID,
									parentDCGroupValue, parentDCFileValue,
									fileName);
							parentDc.delete();
							SDK.getDCAPI().copyDCFile(subDc, parentDc);
							// 处理APP_ACT_HWSIGNATURE_DATA数据
							String queryParentHWDataSql = "SELECT ID,BINDID,BOID,APPID,BOITEMNAME,TASKINSTID,CREATEUSER,CREATETIME,FILENAME,SIGNUSER,SIGNTIME,NOWTYPE,DATA,QRCODE,USERMZ,SORT FROM APP_ACT_HWSIGNATURE_DATA WHERE BINDID = :BINDID  AND BOID =:BOID AND BOITEMNAME = :BOITEMNAME AND FILENAME =:FILENAME ";
							queryMap.put("BINDID", parentBindid);
							queryMap.put("BOID", parentBo.getId());
							queryMap.put("BOITEMNAME", "HQ");
							queryMap.put("FILENAME", fileName);
							List<Map<String, String>> queryParentDataList = DBSql
									.query(queryParentHWDataSql,
											queryMap,
											new RowMapper<Map<String, String>>() {
												public Map<String, String> mapRow(
														ResultSet rs, int index)
														throws SQLException {
													Map<String, String> map = new HashMap<String, String>();
													map.put("ID",
															rs.getString("ID"));
													map.put("BINDID",
															rs.getString("BINDID"));
													map.put("BOID", rs
															.getString("BOID"));
													map.put("APPID", rs
															.getString("APPID"));
													map.put("BOITEMNAME",
															rs.getString("BOITEMNAME"));
													map.put("TASKINSTID",
															rs.getString("TASKINSTID"));
													map.put("CREATEUSER",
															rs.getString("CREATEUSER"));
													map.put("CREATETIME",
															rs.getString("CREATETIME"));
													map.put("FILENAME",
															rs.getString("FILENAME"));
													map.put("SIGNUSER",
															rs.getString("SIGNUSER"));
													map.put("SIGNTIME",
															rs.getString("SIGNTIME"));
													map.put("NOWTYPE",
															rs.getString("NOWTYPE"));
													map.put("DATA", rs
															.getString("DATA"));
													map.put("QRCODE",
															rs.getString("QRCODE"));
													map.put("USERMZ",
															rs.getString("USERMZ"));
													map.put("SORT", rs
															.getString("SORT"));
													return map;
												}
											});
							if (queryParentDataList == null
									|| queryParentDataList.isEmpty()
									|| queryParentDataList.size() == 0) {// 不存在，执行插入
								JSONObject hwJson = new JSONObject();
								hwJson.put("ID", UUIDGener.getUUID());
								hwJson.put("BINDID", parentBindid);
								hwJson.put("BOID", parentBo.getId());
								hwJson.put("APPID", ODConstant.APP_ID);
								hwJson.put("BOITEMNAME", "HQ");
								hwJson.put("TASKINSTID", "xxx");
								hwJson.put("CREATEUSER",
										subHwDataMap.get("CREATEUSER"));
								hwJson.put("CREATETIME",
										subHwDataMap.get("CREATETIME"));
								hwJson.put("FILENAME", fileName);
								hwJson.put("SIGNUSER",
										subHwDataMap.get("SIGNUSER"));
								hwJson.put("SIGNTIME",
										subHwDataMap.get("SIGNTIME"));
								hwJson.put("NOWTYPE", "1");
								hwJson.put("DATA", "");
								hwJson.put("QRCODE", "");
								hwJson.put("USERMZ", "");
								hwJson.put("SORT", "");

								// 调用App
								String sourceAppId = "com.actionsoft.apps.formui.hwsignature";
								// aslp服务地址
								String aslp = "aslp://com.actionsoft.apps.formui.hwsignature/saveHwData";
								// 参数定义列表
								Map<String, Object> params = new HashMap<String, Object>();
								// 手写签批json信息，不允许空值,必填
								params.put("hwjson", hwJson.toString());
								// 插入手写签批数据库记录
								ResponseObject ro = SDK.getAppAPI().callASLP(
										SDK.getAppAPI().getAppContext(
												sourceAppId), aslp, params);
							}

						}
					}
				}
			}
		}
	}
}
